//
//  HGGigIncomeVC.m
//  RedWinMall
//
//  Created by HeDianZhao on 2018/8/3.
//  Copyright © 2018年 HeDianZhao. All rights reserved.
//

#import "HGGigIncomeVC.h"
#import "HGIntegralVC.h"
#import "HGIntegralModel.h"
#import "HGIntegralCell.h"
#import <WebKit/WebKit.h>
#import <AudioToolbox/AudioToolbox.h>
#import "HGPopView.h"

@interface HGGigIncomeHeader : UIView <CAAnimationDelegate>


@end

@implementation HGGigIncomeHeader {
    UIImageView *tapView;
}

- (instancetype)init {
    if (self = [super init]) {
        
        NSData *gif = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"wk"ofType:@"gif"]];
        
        UIImageView *bgImage = [[UIImageView alloc] init];
        UIImage *gifImg = [UIImage sd_animatedGIFWithData:gif];
        bgImage.image = gifImg;
        [bgImage setUserInteractionEnabled:YES];
        [self addSubview:bgImage];

        [bgImage mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self);
        }];
        
        NSArray *arrx = @[@"0.1",@"0.3",@"0.6",@"0.8",@"1",@"1.2",@"1.4",@"1.6"];
        NSArray *arry = @[@"1",@"1.5",@"1.1",@"0.4",@"0.6",@"1.3",@"1.2",@"1"];
        for (int i = 0; i < arrx.count; i++) {
            UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"psc"]];
            [bgImage addSubview:imageView];
            [imageView setUserInteractionEnabled:YES];
            [imageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(setAnimation:)]];

            [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerX.equalTo(bgImage).multipliedBy([arrx[i] floatValue]);
                make.centerY.equalTo(bgImage).multipliedBy([arry[i] floatValue]);
            }];
        }

//        UIImageView *czImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"fuzi"]];
//        czImageView.tag = 1000;
//        [self addSubview:czImageView];
//
//        [czImageView mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.centerY.equalTo(self).multipliedBy(0.8);
//            make.centerX.equalTo(self).multipliedBy(1.4);
//        }];

//        [self layoutIfNeeded];
//        CGRect frame = czImageView.frame;
//        czImageView.layer.anchorPoint = CGPointMake(1, 1);
//        czImageView.frame = frame;

//        CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
//        animation.fromValue = @(0.4 * M_PI);
//        animation.toValue = @(-(M_PI * 0.15));
//        animation.duration = 0.7;
//        animation.removedOnCompletion = NO;
//        animation.repeatCount = MAXFLOAT;
//        animation.fillMode = kCAFillModeForwards;
//        animation.autoreverses = YES;
//        animation.delegate = self;
//
//        [czImageView.layer addAnimation:animation forKey:@"123"];
    }
    return self;
}

#pragma mark - 抖动动画
- (void)setAnimation:(UITapGestureRecognizer *)tap {

    CABasicAnimation* shake = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    //设置抖动幅度
    shake.fromValue = [NSNumber numberWithFloat:+0.1];
    shake.toValue = [NSNumber numberWithFloat:-0.1];
    shake.duration = 0.1;
    shake.autoreverses = NO; //是否重复
    shake.repeatCount = 4;
    shake.delegate = self;
    [shake setValue:@"StartHiddenAnimation" forKey:@"AnimationKey"];
    [tap.view.layer addAnimation:shake forKey:@"StartHiddenAnimation"];
    
    tapView = (UIImageView *)tap.view;
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
    
    if ([[anim valueForKey:@"AnimationKey"] isEqualToString:@"StartHiddenAnimation"]) {
        
        CABasicAnimation *anim1 = [CABasicAnimation animation];
        anim1.keyPath = @"position.y";
        anim1.toValue = @400;
    
        CABasicAnimation *anim2 = [CABasicAnimation animation];
        anim2.keyPath = @"opacity";
        anim2.toValue = @0;
        
        CAAnimationGroup *group = [CAAnimationGroup animation];
        group.duration = 0.5;
        group.removedOnCompletion = NO;
        group.fillMode = kCAFillModeForwards;
        group.delegate = self;
        group.animations = @[anim1, anim2];
        [tapView.layer addAnimation:group forKey:@"position"];
        
    } else {
        tapView.alpha = 0;
        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"money" ofType:@"mp3"];
        NSURL *fileUrl = [NSURL URLWithString:filePath];
        SystemSoundID soundID = 0;
        AudioServicesCreateSystemSoundID((__bridge CFURLRef)(fileUrl), &soundID);
        AudioServicesAddSystemSoundCompletion(soundID,NULL,NULL,soundCompleteCallBack,NULL);
        
        AudioServicesPlaySystemSound(soundID);
    }
}

void soundCompleteCallBack(SystemSoundID soundID, void *clientData)
{
    NSLog(@"播放完成");
}
@end


@interface HGGigIncomeVC ()

@property (nonatomic, strong) HGGigIncomeHeader *headerView;

@property (copy,nonatomic)NSMutableArray <HGIntegralModel *> *intefralModels;

@property (nonatomic, strong) NSArray<NSDictionary *> *buttonCofigs;

@property (nonatomic, strong) NSMutableArray<UILabel *> *labels;


@property (nonatomic, assign) NSInteger redSocre;
@end


@implementation HGGigIncomeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"积分中心";
    
    [self initDatas];
    
    [self initSubViews];
}

- (void)initDatas {
    
    [[LMJRequestManager sharedManager] GET:KBaseURL(@"app/acct/score") parameters:nil completion:^(LMJBaseResponse *response) {
        if (response.responseModel.status == 1) {
            
            _redSocre = [response.responseModel.data[@"redScore"] integerValue];
            NSArray *datas = @[response.responseModel.data[@"greyScoreText"],response.responseModel.data[@"redScoreText"],response.responseModel.data[@"yellowScoreText"],response.responseModel.data[@"blueScoreText"],@""];
            [_labels enumerateObjectsUsingBlock:^(UILabel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                obj.text = datas[idx];
            }];
        }
    }];
}

#pragma mark - 
- (void)initSubViews {
    
    UIView *tableView = [[UIView alloc] init];
    [self.view addSubview:tableView];
    
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.headerView.mas_bottom);
        make.left.right.equalTo(self.view);
        make.height.offset(64 * 4);
    }];
    
    [self.buttonCofigs enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        UIView *bgView = [[UIView alloc] init];
        bgView.backgroundColor = [UIColor whiteColor];
        bgView.tag = 1000+idx;
        [bgView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pushVC:)]];
        [tableView addSubview:bgView];
    
        UILabel *leftLabel = [[UILabel alloc] init];
        leftLabel.text = obj[@"promtor"];
        leftLabel.backgroundColor = obj[@"color"];
        leftLabel.textColor = [UIColor whiteColor];
        leftLabel.textAlignment = NSTextAlignmentCenter;
        leftLabel.font = [UIFont systemFontOfSize:12];
        [bgView addSubview:leftLabel];
        
        [leftLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(40, 28));
            make.centerY.equalTo(bgView);
            make.left.offset(15);
        }];
        
        UIButton *promtorButton = [[UIButton alloc] init];
        promtorButton.userInteractionEnabled = NO;
        [promtorButton setTitle:@"积分明细" forState:(UIControlStateNormal)];
        [promtorButton setImage:[UIImage imageNamed:@"xiala"] forState:(UIControlStateNormal)];
        [promtorButton setTitleColor:kColorDefult forState:(UIControlStateNormal)];
        promtorButton.titleLabel.font = [UIFont systemFontOfSize:14];
        [bgView addSubview:promtorButton];
        
        [promtorButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(leftLabel);
            make.left.equalTo(leftLabel.mas_right).offset(15);
        }];
        
        UILabel *soceLabel = [[UILabel alloc] init];
        soceLabel.text = @"00.00";
        soceLabel.textColor = kColorDefult;
        soceLabel.font = [UIFont systemFontOfSize:19];
        [bgView addSubview:soceLabel];
        
        [soceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(leftLabel);
            make.left.equalTo(promtorButton.mas_right).offset(20);
        }];
        
        [self.labels addObject:soceLabel];
        
        NSString *titleName = obj[@"name"];
        if (titleName.length != 0) {
            UIButton *sendeButton = [[UIButton alloc] init];
            [sendeButton setTitle:titleName forState:(UIControlStateNormal)];
            [sendeButton setBackgroundImage:[UIImage imageNamed:titleName] forState:(UIControlStateNormal)];
            sendeButton.titleLabel.font = [UIFont systemFontOfSize:12];
            [sendeButton addTarget:self action:@selector(cilkAction:) forControlEvents:(UIControlEventTouchUpInside)];
            [bgView addSubview:sendeButton];
            
            [sendeButton mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(leftLabel);
                make.right.offset(-15);
            }];
        }
        
        UIView *lineView = [[UIView alloc] init];
        lineView.backgroundColor = kColorBackground;
        [bgView addSubview:lineView];
        
        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.bottom.equalTo(bgView);
            make.left.offset(15);
            make.height.offset(1);
        }];
    }];
    
    [tableView.subviews mas_distributeViewsAlongAxis:(MASAxisTypeVertical) withFixedSpacing:0 leadSpacing:0 tailSpacing:0];
    [tableView.subviews mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.left.equalTo(tableView);
        make.centerX.equalTo(tableView);
        make.height.offset(64);
    }];
}

#pragma mark - 兑换惊喜
- (void)cilkAction:(UIButton *)sender {
    
    HGPopView *view = [[HGPopView alloc] initWithFrame:CGRectMake(0, 0, 300, 190)];
    view.soce = _redSocre;
    view.closeBlock = ^{
        [LEEAlert closeWithCompletionBlock:nil];
    };
    view.callBack = ^(NSInteger socre) {
        if (socre < 108) {
            [LEEAlert closeWithCompletionBlock:nil];
            [[XNProgressHUD shared] showInfoWithTitle:@"最低消耗108红积分"];
            return;
        }
        [[XNProgressHUD shared] showLoadingWithTitle:@"兑换中" maskType:(XNProgressHUDMaskTypeBlack)];
        [[LMJRequestManager sharedManager] GET:KBaseURL(@"app/acct/change") parameters:@{@"score" : [NSNumber numberWithInteger:socre]} completion:^(LMJBaseResponse *response) {
            [[XNProgressHUD shared] dismiss];
            if (response.responseModel.status == 1) {
                [self initDatas];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [[XNProgressHUD shared] showSuccessWithTitle:response.responseModel.message];
                });
            } else {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [[XNProgressHUD shared] showErrorWithTitle:response.responseModel.message];
                });
            }
            [LEEAlert closeWithCompletionBlock:nil];
        }];
    };
    [LEEAlert alert].config
    .LeeCustomView(view)
    .LeeHeaderInsets(UIEdgeInsetsMake(0, 0, 0, 0))
    .LeeClickBackgroundClose(YES)
    .LeeShow();
    
}

- (void)pushVC:(UITapGestureRecognizer *)tap {
    HGIntegralVC *vc = [[HGIntegralVC alloc] init];
    vc.type = tap.view.tag - 1000;
    vc.title = _buttonCofigs[tap.view.tag - 1000][@"promtor"];
    [self.navigationController pushViewController:vc animated:YES];
}

- (NSArray<NSDictionary *> *)buttonCofigs {
    if (!_buttonCofigs) {
        _buttonCofigs = @[@{
                              @"name" : @"",
                              @"color" : kColorWithFloat(0x7f7f7f),
                              @"promtor" : @"灰积分"
                              },@{
                              @"name" : @"兑换惊喜",
                              @"color" : kColorWithFloat(0xea4436),
                              @"promtor" : @"红积分"
                              },@{
                              @"name" : @"一键挖矿",
                              @"color" : kColorWithFloat(0xfca805),
                              @"promtor" : @"黄积分"
                              },@{
                              @"name" : @"兑换商品",
                              @"color" : kColorWithFloat(0x4286f5),
                              @"promtor" : @"蓝积分"
                              }];
    }
    return _buttonCofigs;
}

- (NSMutableArray<UILabel *> *)labels {
    if (!_labels) {
        _labels = [@[] mutableCopy];
    }
    return _labels;
}

//#pragma mark - 获取数据
//- (void)initDatas {
//
//    [[LMJRequestManager sharedManager] GET:KBaseURL(@"/app/acct/mine/info") parameters:@{@"page":@1} completion:^(LMJBaseResponse *response) {
//        if (response.responseModel.status == 1) {
//            _intefralModels = [HGIntegralModel mj_objectArrayWithKeyValuesArray:response.responseModel.data[@"rows"]];
//            [_tableView reloadData];
//        }
//    }];
//}
//
//
//- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//    return _intefralModels.count;
//}
//
//- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//    HGIntegralCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HGIntegralCell"];
//    cell.model = _intefralModels[indexPath.row];
//    return cell;
//}
//
//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
//    UITableViewHeaderFooterView *hederView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"UITableViewHeaderFooterView"];
//    hederView.contentView.backgroundColor = [UIColor whiteColor];
//    UIButton *hederButton = [[UIButton alloc] init];
//    [hederButton setTitle:@" 挖矿记录" forState:(UIControlStateNormal)];
//    [hederButton setTitleColor:kColorDefult forState:(UIControlStateNormal)];
//    hederButton.titleLabel.font = [UIFont systemFontOfSize:14];
//    [hederButton setImage:[UIImage imageNamed:@"tip"] forState:(UIControlStateNormal)];
//    [hederView.contentView addSubview:hederButton];
//
//    [hederButton mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.centerY.equalTo(hederView);
//        make.left.offset(15);
//    }];
//
//    UIView *lineView = [[UIView alloc] init];
//    lineView.backgroundColor = kColorBackground;
//    [hederView addSubview:lineView];
//    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.right.bottom.equalTo(hederView);
//        make.height.offset(1);
//        make.left.offset(15);
//    }];
//
//    return hederView;
//}
//
//- (UITableView *)tableView {
//    if (!_tableView){
//        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:(UITableViewStylePlain)];
//        _tableView.delegate = self;
//        _tableView.dataSource = self;
//        _tableView.rowHeight = 46;
//        _tableView.tableHeaderView = self.headerView;
//        _tableView.tableFooterView = [UIView new];
//        [_tableView registerClass:[UITableViewHeaderFooterView class] forHeaderFooterViewReuseIdentifier:@"UITableViewHeaderFooterView"];
//        _tableView.sectionHeaderHeight = 40;
//        [self.view addSubview:_tableView];
//
//        [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.edges.equalTo(self.view);
//        }];
//    }
//    return _tableView;
//}

- (HGGigIncomeHeader *)headerView {
    if (!_headerView) {
        _headerView = [[HGGigIncomeHeader alloc] init];
        [self.view addSubview:_headerView];
        [_headerView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.equalTo(self.view);
            make.height.offset(180);
        }];
    }
    return _headerView;
}

@end
